<template>
  <div class="product-container">
    <!-- 左侧分类导航 -->
    <div class="category-nav">
      <div class="type-selector">
        <button
            :class="{ active: activeType === 1 }"
            @click="switchType(1)"
        >
          菜品
        </button>
        <button
            :class="{ active: activeType === 2 }"
            @click="switchType(2)"
        >
          套餐
        </button>
      </div>

      <div class="category-list">
        <div
            v-for="category in filteredCategories"
            :key="category.id"
            :class="{ active: activeCategory === category.id }"
            @click="loadCategoryData(category)"
        >
          {{ category.name }}
        </div>
      </div>
    </div>

    <!-- 右侧商品展示 -->
    <div class="product-display">
      <div class="search-bar">
        <el-input
            v-model="searchQuery"
            placeholder="搜索菜品或套餐"
            clearable
            @clear="handleSearchClear"
            @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </div>

      <div v-if="loading" class="loading-container">
        <el-icon class="is-loading" size="30">
          <Loading />
        </el-icon>
        <span>加载中...</span>
      </div>

      <div v-else class="product-grid">
        <!-- 菜品卡片 -->
        <div
            v-for="dish in currentDishes"
            :key="dish.id"
            class="product-card"
        >
          <div class="product-image">
            <img :src="getFullImageUrl(dish.image)" :alt="dish.name" />
            <div v-if="dish.status === 0" class="sold-out">已售罄</div>
          </div>
          <div class="product-info">
            <h3>{{ dish.name }}</h3>
            <p class="description">{{ dish.description }}</p>
            <div class="product-footer">
              <span class="price">¥{{ dish.price }}</span>
              <el-button
                  type="primary"
                  size="small"
                  :disabled="dish.status === 0"
                  @click="dish.flavors && dish.flavors.length > 0 ? showFlavorDialog(dish) : addToCart(dish)"
                  class="add-btn"
              >
                {{ dish.flavors && dish.flavors.length > 0 ? '选规格' : '加入购物车' }}
              </el-button>
            </div>
          </div>
        </div>

        <!-- 套餐卡片 -->
        <div
            v-for="setmeal in currentSetmeals"
            :key="setmeal.id"
            class="product-card"
        >
          <div class="product-image">
            <img :src="getFullImageUrl(setmeal.image)" :alt="setmeal.name" />
            <div v-if="setmeal.status === 0" class="sold-out">已售罄</div>
          </div>
          <div class="product-info">
            <h3>{{ setmeal.name }}</h3>
            <p class="description">{{ setmeal.description }}</p>
            <div class="product-footer">
              <span class="price">¥{{ setmeal.price }}</span>
              <div class="btn-group">
                <el-button
                    type="info"
                    size="small"
                    @click="showSetmealDetail(setmeal)"
                    class="detail-btn"
                >
                  查看详情
                </el-button>
                <el-button
                    type="primary"
                    size="small"
                    :disabled="setmeal.status === 0"
                    @click="addToCart(setmeal)"
                    class="add-btn"
                >
                  加入购物车
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <div v-if="currentDishes.length === 0 && currentSetmeals.length === 0" class="empty-tip">
          <el-icon :size="60" color="#909399">
            <Box />
          </el-icon>
          <p>暂无数据，请选择其他分类</p>
        </div>
      </div>
    </div>

    <!-- 口味选择对话框 -->
    <el-dialog v-model="flavorDialogVisible" :title="`选择${selectedDish?.name}规格`" class="custom-dialog flavor-dialog" width="400px">
      <div class="flavor-container">
        <div class="selected-dish-info">
          <img :src="getFullImageUrl(selectedDish?.image)" :alt="selectedDish?.name" class="selected-dish-image" />
          <div class="selected-dish-details">
            <h3>{{ selectedDish?.name }}</h3>
            <p class="price">¥{{ selectedDish?.price }}</p>
          </div>
        </div>
        
        <div class="flavor-list">
          <div v-for="flavor in selectedDish?.flavors" :key="flavor.id" class="flavor-item">
            <h4 class="flavor-title">{{ flavor.name }}</h4>
            <el-radio-group v-model="selectedFlavors[flavor.name]" class="flavor-options">
              <el-radio
                  v-for="option in parseFlavorOptions(flavor.value)"
                  :key="option"
                  :label="option"
                  border
              >
                {{ option }}
              </el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="flavorDialogVisible = false" plain>取消</el-button>
          <el-button type="primary" @click="confirmFlavorSelection" class="confirm-btn">加入购物车</el-button>
        </div>
      </template>
    </el-dialog>

<!-- 套餐详情对话框 -->
<el-dialog v-model="setmealDetailVisible" :title="`${selectedSetmeal?.name}套餐详情`" class="custom-dialog setmeal-dialog" width="500px">
  <div class="setmeal-detail-container">
    <div class="setmeal-header">
      <div class="setmeal-image-container">
        <img :src="getFullImageUrl(selectedSetmeal?.image)" :alt="selectedSetmeal?.name" class="setmeal-image" />
      </div>
      <div class="setmeal-info">
        <h3 class="setmeal-title">{{ selectedSetmeal?.name }}</h3>
        <div class="setmeal-price">¥{{ selectedSetmeal?.price }}</div>
        <div class="setmeal-description">{{ selectedSetmeal?.description }}</div>
      </div>
    </div>
    
    <div class="setmeal-divider">
      <span>套餐内容</span>
    </div>
    
    <div class="setmeal-dishes-list">
      <div v-for="dish in selectedSetmeal?.setmealDishes" :key="dish.id" class="setmeal-dish-item">
        <div class="dish-info">
          <div class="dish-name">{{ dish.name }}</div>
          <div class="dish-copies">× {{ dish.copies }}</div>
        </div>
      </div>
    </div>
  </div>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="setmealDetailVisible = false" plain>关闭</el-button>
      <el-button 
        type="primary" 
        @click="addToCart(selectedSetmeal)" 
        :disabled="selectedSetmeal?.status === 0"
        class="confirm-btn"
      >
        加入购物车
      </el-button>
    </div>
  </template>
</el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from 'vue'
import {Search, Loading, Box} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'
import {getAllCategory} from "@/api/category";
import {getDishesByCategoryId} from "@/api/dish";
import {fileViewPath} from "@/utils/file";
import {getSetMealsAndRelatedDishesByCategory} from "@/api/setmeal";

// 响应式数据
const activeType = ref(1) // 1: 菜品, 2: 套餐(默认选中菜品)
const activeCategory = ref(null)//选中的分类

const searchQuery = ref('')
const flavorDialogVisible = ref(false)
const selectedDish = ref(null)
const selectedFlavors = ref({})
const setmealDetailVisible = ref(false)
const selectedSetmeal = ref(null)
const loading = ref(false)

// 当前显示的数据
const currentDishes = ref([])
const currentSetmeals = ref([])

// 分类数据
const categories = ref([])

// 根据当前选择的类型过滤分类
const filteredCategories = computed(() => {
  return categories.value.filter(category => category.type === activeType.value);
});

//获取所有的分类信息
const fetchAllCategories = async () =>{
  if(loading.value) return
  try{
    loading.value = true
    const res = await getAllCategory()
    if(res.code === '200'){
      categories.value = res.data
      // 默认加载第一个菜品分类的商品
      const firstDishCategory = categories.value.find(c => c.type === 1)
      if (firstDishCategory) {
        await loadCategoryData(firstDishCategory)
      }
    }else{
      ElMessage.error('获取分类信息失败')
    }
  } catch(e){
    ElMessage.error('获取分类信息失败')
  } finally {
    loading.value = false;
  }
}

//将所有的分类信息获取并存放在categories中然后根据type区分
const loadCategoryData = async (category) => {
  if (!category) return

  activeCategory.value = category.id
  loading.value = true

  try {
    await new Promise(resolve => setTimeout(resolve, 200))

    if (category.type === 1) {//如果选中的菜品
      // 加载菜品数据
      currentDishes.value = await fetchDishesByCategory(activeCategory.value)
      currentSetmeals.value = []
    } else if (category.type === 2) {//如果选中的是套餐
      // 加载套餐数据
      currentSetmeals.value = await fetchSetmealsByCategory(activeCategory.value)
      currentDishes.value = []
    }
  } catch (error) {
    console.error('数据加载失败:', error)
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

// 方法
const switchType = (type) => {
  activeType.value = type
  // 重置选中分类
  const firstCategory = categories.value.find(c => c.type === type)
  if (firstCategory) {
    loadCategoryData(firstCategory)
  } else {
    currentDishes.value = []
    currentSetmeals.value = []
  }
}

// 获取菜品数据
const fetchDishesByCategory = async (categoryId) => {
  try {
    const submitData = {
      categoryId: categoryId,
      name: ''
    }
    const res = await getDishesByCategoryId(submitData)
    if(res.code === '200'){
      return res.data || []
    } else {
      console.log(res.msg || '获取菜品信息失败')
    }
  } catch (error) {
    console.error('获取菜品失败:', error)
    ElMessage.error('获取菜品信息失败')
  }
  return []
}

// 获取套餐数据
const fetchSetmealsByCategory = async (categoryId) => {
  try {
    const submitData = {
      categoryId: categoryId,
      name: ''
    }
    const res = await getSetMealsAndRelatedDishesByCategory(submitData)
    if(res.code === '200'){
      return res.data || []
    } else {
      console.log(res.msg || '获取套餐信息失败')
    }
  } catch (error) {
    console.error('获取套餐失败:', error)
    ElMessage.error('获取套餐信息失败')
  }
  return []
}

const handleSearch = async () => {
  if (!searchQuery.value.trim()) return

  loading.value = true
  try {
    if (activeType.value === 1) {//菜品搜索
      // 搜索菜品
      const params = {
        name: searchQuery.value
      }
      const res = await getDishesByCategoryId(params)
      if (res.code === '200') {
        currentDishes.value = res.data || []
      } else {
        ElMessage.error(res.msg || '搜索菜品失败')
      }
      currentSetmeals.value = []
    } else {//套餐搜索
      // 搜索套餐
      const params = {
        name: searchQuery.value
      }
      const res = await getSetMealsAndRelatedDishesByCategory(params)
      if (res.code === '200') {
        currentSetmeals.value = res.data || []
      } else {
        ElMessage.error(res.msg || '搜索套餐失败')
      }
      currentDishes.value = []
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const handleSearchClear = () => {
  searchQuery.value = ''
  const currentCategory = categories.value.find(c => c.id === activeCategory.value)
  if (currentCategory) {
    loadCategoryData(currentCategory)
  }
}

//图片访问路径
const getFullImageUrl = (imagePath) => {
  if (!imagePath) return ''
  return `${fileViewPath}${formatImagePath(imagePath)}`
}

// 路径格式化函数（处理Windows路径）
const formatImagePath = (path) => {
  if (!path) return '';
  return path.replace(/\\/g, '/'); // 将反斜杠替换为斜杠
};

const parseFlavorOptions = (value) => {
  try {
    return JSON.parse(value)
  } catch {
    return value.split(',')
  }
}

const showFlavorDialog = (dish) => {
  selectedDish.value = dish
  selectedFlavors.value = {}
  // 初始化选中第一个选项
  dish.flavors.forEach(flavor => {
    const options = parseFlavorOptions(flavor.value)
    if (options.length > 0) {
      selectedFlavors.value[flavor.name] = options[0]
    }
  })
  flavorDialogVisible.value = true
}

const confirmFlavorSelection = () => {
  if (!selectedDish.value) return

  const item = {
    ...selectedDish.value,
    selectedFlavors: {...selectedFlavors.value}
  }

  addToCart(item)
  flavorDialogVisible.value = false
}

const showSetmealDetail = (setmeal) => {
  selectedSetmeal.value = setmeal
  setmealDetailVisible.value = true
}

// 在 Products.vue 的 script 部分引入购物车 API
import { addFoodToCart } from "@/api/cart";

const addToCart = async (item) => {
  try {
    // 判断是菜品还是套餐
    // 通过检查 item 中是否存在 flavors 属性来判断是菜品
    // 通过检查 item 中是否存在 setmealDishes 属性来判断是套餐
    const isDish = item.flavors !== undefined;
    const isSetMeal = item.setmealDishes !== undefined;
    
    const cartData = {
      name: item.name,
      image: item.image,
      dishId: isDish ? item.id : null,
      setmealId: isSetMeal ? item.id : null,
      dishFlavor: item.selectedFlavors ? JSON.stringify(item.selectedFlavors) : null,
      number: 1,
      amount: item.price
    };

    const res = await addFoodToCart(cartData);
    if (res.code === '200') {
      ElMessage.success(`${item.name} 已添加到购物车`);
    } else {
      ElMessage.error(res.msg || '添加到购物车失败');
    }
  } catch (error) {
    console.error('添加到购物车失败:', error);
    ElMessage.error('添加到购物车失败');
  }
}

// 初始化
onMounted(() => {
  fetchAllCategories()
})
</script>

<style scoped>
.product-container {
  display: flex;
  height: auto;
  min-height: calc(100vh - 200px);
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.category-nav {
  width: 180px;
  background-color: #f9f9f9;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
  max-height: calc(100vh - 200px);
  overflow-y: auto;
}

.type-selector {
  display: flex;
  padding: 15px 10px;
  border-bottom: 1px solid #eee;
  background-color: #fff;
}

.type-selector button {
  flex: 1;
  padding: 8px 0;
  border: none;
  background: none;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  transition: all 0.3s;
  border-radius: 4px;
}

.type-selector button:hover {
  color: #ff6b6b;
}

.type-selector button.active {
  color: #ff6b6b;
  font-weight: bold;
  border-bottom: 2px solid #ff6b6b;
}

.category-list {
  flex: 1;
  overflow-y: auto;
}

.category-list div {
  padding: 12px 20px;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  transition: all 0.3s;
  border-left: 3px solid transparent;
  position: relative;
}

.category-list div:hover {
  background-color: #f0f0f0;
  color: #ff6b6b;
}

.category-list div.active {
  background-color: #fff;
  color: #ff6b6b;
  font-weight: bold;
  border-left: 3px solid #ff6b6b;
}

.product-display {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #fff;
  max-height: calc(100vh - 200px);
}

.search-bar {
  margin-bottom: 20px;
  max-width: 400px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #666;
}

.loading-container .el-icon {
  margin-bottom: 10px;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;
}

.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  grid-column: 1 / -1;
  padding: 40px 0;
  color: #909399;
  text-align: center;
}

.empty-tip .el-icon {
  margin-bottom: 16px;
}

.empty-tip p {
  margin: 0;
  font-size: 14px;
}

.product-card {
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s, box-shadow 0.3s;
  display: flex;
  flex-direction: column;
  height: 100%;
  border: 1px solid #f0f0f0;
}

.product-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.product-image {
  position: relative;
  height: 160px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s;
}

.product-card:hover .product-image img {
  transform: scale(1.05);
}

.sold-out {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.product-info {
  padding: 15px;
  display: flex;
  flex-direction: column;
  flex: 1;
}

.product-info h3 {
  margin: 0 0 8px;
  font-size: 16px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.description {
  font-size: 12px;
  color: #999;
  margin: 0 0 12px;
  height: 36px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  flex: 1;
}

.product-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
}

.price {
  font-size: 18px;
  font-weight: bold;
  color: #ff6b6b;
}

.btn-group {
  display: flex;
  gap: 5px;
}

.add-btn {
  background-color: #ff6b6b;
  border-color: #ff6b6b;
  padding: 6px 12px;
  font-size: 13px;
}

.add-btn:hover {
  background-color: #ff5252;
  border-color: #ff5252;
}

.detail-btn {
  background-color: #f0f0f0;
  border-color: #f0f0f0;
  color: #666;
  padding: 6px 12px;
  font-size: 13px;
}

.detail-btn:hover {
  background-color: #e0e0e0;
  border-color: #e0e0e0;
}

/* 套餐详情对话框样式 */
.setmeal-dialog :deep(.el-dialog__header) {
  padding: 15px 20px;
  margin: 0;
  border-bottom: 1px solid #f0f0f0;
  background-color: #f9f9f9;
}

.setmeal-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.setmeal-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.setmeal-dialog :deep(.el-dialog__footer) {
  padding: 15px 20px;
  border-top: 1px solid #f0f0f0;
}

.setmeal-detail-container {
  display: flex;
  flex-direction: column;
}

.setmeal-header {
  display: flex;
  padding: 20px;
  background-color: #fff8f8;
  border-bottom: 1px solid #f0f0f0;
}

.setmeal-image-container {
  width: 120px;
  height: 120px;
  margin-right: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.setmeal-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.setmeal-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.setmeal-title {
  margin: 0 0 10px;
  font-size: 20px;
  color: #333;
  font-weight: 600;
}

.setmeal-price {
  font-size: 22px;
  font-weight: bold;
  color: #ff6b6b;
  margin-bottom: 10px;
}

.setmeal-description {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.setmeal-divider {
  position: relative;
  text-align: center;
  margin: 15px 0;
  height: 20px;
}

.setmeal-divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 20px;
  right: 20px;
  height: 1px;
  background-color: #eee;
  z-index: 1;
}

.setmeal-divider span {
  position: relative;
  display: inline-block;
  padding: 0 15px;
  background-color: #fff;
  color: #666;
  font-size: 14px;
  z-index: 2;
}

.setmeal-dishes-list {
  padding: 0 20px 20px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  max-height: 300px;
  overflow-y: auto;
}

.setmeal-dish-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-radius: 8px;
  background-color: #f9f9f9;
  transition: all 0.3s;
}

.setmeal-dish-item:hover {
  background-color: #f0f0f0;
  transform: translateY(-2px);
}

.dish-image-container {
  width: 50px;
  height: 50px;
  border-radius: 6px;
  overflow: hidden;
  margin-right: 12px;
  border: 1px solid #eee;
}

.dish-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.dish-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dish-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.dish-copies {
  font-size: 14px;
  color: #666;
  margin-left: 10px;
}

@media (max-width: 768px) {
  .setmeal-header {
    flex-direction: column;
  }
  
  .setmeal-image-container {
    width: 100%;
    height: 180px;
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .setmeal-dishes-list {
    grid-template-columns: 1fr;
  }
}



/* 添加选规格对话框样式 */
.flavor-dialog :deep(.el-dialog__header) {
  padding: 15px 20px;
  margin: 0;
  border-bottom: 1px solid #f0f0f0;
  background-color: #f9f9f9;
}

.flavor-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.flavor-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.flavor-dialog :deep(.el-dialog__footer) {
  padding: 15px 20px;
  border-top: 1px solid #f0f0f0;
}

.flavor-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.selected-dish-info {
  display: flex;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px dashed #eee;
}

.selected-dish-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 8px;
  margin-right: 15px;
  border: 1px solid #f0f0f0;
}

.selected-dish-details h3 {
  margin: 0 0 8px;
  font-size: 16px;
  color: #333;
}

.selected-dish-details .price {
  font-size: 18px;
  font-weight: bold;
  color: #ff6b6b;
  margin: 0;
}

.flavor-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.flavor-item {
  margin-bottom: 5px;
}

.flavor-title {
  font-size: 15px;
  margin: 0 0 10px;
  color: #333;
  font-weight: 500;
}

.flavor-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.flavor-options :deep(.el-radio) {
  margin-right: 0;
  margin-bottom: 10px;
}

.flavor-options :deep(.el-radio.is-bordered) {
  padding: 8px 15px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.flavor-options :deep(.el-radio.is-bordered.is-checked) {
  border-color: #ff6b6b;
  background-color: #fff8f8;
}

.flavor-options :deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #ff6b6b;
  border-color: #ff6b6b;
}

.flavor-options :deep(.el-radio__label) {
  font-size: 14px;
  padding-left: 6px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.confirm-btn {
  background-color: #ff6b6b;
  border-color: #ff6b6b;
  padding: 10px 20px;
}

.confirm-btn:hover {
  background-color: #ff5252;
  border-color: #ff5252;
}

/* 保留原有的媒体查询样式... */
</style>
